const passport = require("passport");
const jwt = require("jsonwebtoken");
const LocalStrategy = require("passport-local").Strategy;
const BearerStrategy = require("passport-http-bearer").Strategy;
const jwt_config = require("config").get("jwt_config");
const secretKey = jwt_config.get("secretKey");
const expiresIn = jwt_config.get("expiresIn");
const { login } = require("../services/ManagerService");

//配置验证策略
module.exports.initialize = function () {
  passport.use(
    new LocalStrategy(function (username, password, done) {
      //验证登录
      login(username, password, function (err, user) {
        if (err) {
          return done(err);
        }
        return done(null, user);
      });
    })
  );
  passport.use(
    new BearerStrategy(function (token, done) {
      //携带token验证
      jwt.verify(token, secretKey, function (err, decoded) {
        if (err) return done("验证错误:" + err);
        return done(null, decoded);
      });
    })
  );
};
// 登录验证
module.exports.login = function (req, res, next) {
  passport.authenticate("local", function (err, user) {
    if (err) return res.sendResult(500, null, err);
    if (!user) return res.sendResult(400, null, "参数错误");
    const token = jwt.sign({ uid: user.id, rid: user.role_id }, secretKey, {
      expiresIn,
    });
    user.token = `Bearer ${token}`;
    return res.sendResult(200, user, "登录成功");
  })(req, res, next);
};

//token 验证
module.exports.tokenAuth = function (req, res, next) {
  passport.authenticate(
    "bearer",
    { session: false },
    function (err, userToken, info, status) {
      if (err) {
        return res.sendResult(400, null, "无效token," + err);
      }
      if (!userToken) {
        return res.sendResult(400, null, "无效token");
      }
      req.userInfo = {
        uid: userToken["uid"],
        rid: userToken["rid"],
      };
      next();
    }
  )(req, res, next);
};
